import { createAction } from 'redux-actions'
import { INIT_MAIN_PAGE_B_TYPE, UPDATE_MAIN_PAGE_B_TYPE, GET_COMPOANY_INFO_TYPE } from './type'
import {
  checkUserHaveCompanyApply,
  operatorCenterInfo,
  updateCompanyInfo,
  myCenterNumbers,
  companyLiveList
} from 'src/utils/RequestAPI'
import { DeviceEventEmitter } from 'react-native'
/* sync */

export const INIT_MAIN_PAGE_B_ACTION = createAction(
  INIT_MAIN_PAGE_B_TYPE,
  payload => payload
)

export const UPDATE_MAIN_PAGE_B_ACTION = createAction(
  UPDATE_MAIN_PAGE_B_TYPE,
  payload => payload
)

/* async */
export const DO_REQUEST_MAIN_PAGE_B_ACTION = createAction(
  UPDATE_MAIN_PAGE_B_TYPE,
  ({ userId } = {}) => {
    return new Promise((resolve, reject) => {
      let haveCompanyApply
      checkUserHaveCompanyApply({})
        .then(res => {
          const { companyId, checkStatus } = res.data
          haveCompanyApply = {
            ...res.data,
            companyDone: companyId && checkStatus === 1
          }
          DeviceEventEmitter.emit('companyIdChanged', companyId)
          if (companyId) {
            // DeviceEventEmitter.emit('companyIdChanged', companyId)
            return Promise.all([operatorCenterInfo({ headers: { companyId } }),
            myCenterNumbers({
              headers: { companyId },
              params: {
                type: 'B',
                userId
              }
            }), companyLiveList({
              headers: { companyId },
              params: {
                page: '1',
                limit: '999'
              }
            })])
          } else {
            resolve({ haveCompanyApply })
          }
        }).then(([operatorCenterInfo, myCenterNumbers, companyLiveList]) => {
          const top = myCenterNumbers.data
          resolve({
            ...operatorCenterInfo.data, top, haveCompanyApply, companyLiveList
          })
        })
        .catch(() => {
          reject()
        })
    })
  }
)
/* 修改公司信息 */
export const DO_REQUEST_CHANGE_COMPANY_INFO_ACTION = createAction(
  UPDATE_MAIN_PAGE_B_TYPE,
  args => {
    return new Promise((resolve, reject) => {
      let haveCompanyApply
      updateCompanyInfo(args).then(() => {
        return checkUserHaveCompanyApply({})
      }).then(res => {
        const { companyId, checkStatus } = res.data
        haveCompanyApply = {
          ...res.data,
          companyDone: companyId && checkStatus === 1
        }
        if (companyId) {
          return operatorCenterInfo({ headers: { companyId } })
        } else {
          return { data: {} }
        }
      }).then(res => {
        resolve({
          ...res.data,
          haveCompanyApply
        })
      })
        .catch(() => {
          reject()
        })
    })
  }
)
export const GET_COMPOANY_INFO = createAction(GET_COMPOANY_INFO_TYPE, payload => payload)